Skip to main content

Reverse Linked List

LeetCode 206 | Difficulty: Easy​

Easy

Problem Description​

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

- The number of nodes in the list is the range `[0, 5000]`.

- `-5000 <= Node.val <= 5000`

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

Topics: Linked List, Recursion


Approach​

Linked List​

Use pointer manipulation. Common techniques: dummy head node to simplify edge cases, fast/slow pointers for cycle detection and middle finding, prev/curr/next pattern for reversal.

When to use

In-place list manipulation, cycle detection, merging lists, finding the k-th node.


Solutions​

Solution 1: C# (Best: 96 ms)​

MetricValue
Runtime96 ms
Memory23.8 MB
Date2019-12-15
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null)
{
return head;
}
ListNode rev = null;
while (head!=null)
{
ListNode temp = head.next;
head.next = rev;
rev = head;
head = temp;
}
return rev;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2017-09-22) β€” 172 ms, N/A​

/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode rev = null;
while (head != null)
{
ListNode temp = head;
head = head.next;
temp.next = rev;
rev = temp;
}
return rev;
}
}

Complexity Analysis​

ApproachTimeSpace
Linked List$O(n)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Draw the pointer changes before coding. A dummy head node simplifies edge cases.